package game;

import java.awt.*; 
import java.awt.event.*; 
import java.awt.geom.*; 
import javax.swing.*; 
//生产不同形状的方块 
class ShapeMaker{ 
private static float dx=30; 
private static float dy=30; 
public static GeneralPath makeShapeA(float x,float y){//(X,Y)为画此方块时的左上角 
GeneralPath s=new GeneralPath(); 
s.moveTo(x,y); 
s.lineTo(x+dx,y); 
s.lineTo(x+dx,y+4*dy); 
s.lineTo(x,y+4*dy); 
s.closePath(); 
s.moveTo(x,y+dy); 
s.lineTo(x+dx,y+dy); 
s.moveTo(x,y+2*dy); 
s.lineTo(x+dx,y+2*dy); 
s.moveTo(x,y+3*dy); 
s.lineTo(x+dx,y+3*dy); 
return s; 
} 
} 
//一个面板,显示方块 
class GamePanel extends JPanel implements ActionListener{ 
private float dx;//每个小格的宽度,也是每个小方块的宽度 
private float dy;//每个小格的高度,也是每个小方块的高度 
private AffineTransform t;//几何变换对象 
private int x; 
private int y;//X,Y以方格为单位的方块位置 
private int i;//控制几何变换的角度 
private int flag;//控制方块移动方向 
GeneralPath shape;//特定方块对象 
private Timer timer = new Timer(1000, this);//定时器,移动方块时使用 

public GamePanel(float dx,float dy){ 
this.dx=dx; 
this.dy=dy; 
x=0; 
y=0; 
i=1; 
flag=0; 
t=AffineTransform.getRotateInstance(0, 6*dx,0*dy); 
timer.start(); 
} 
public void paintComponent(Graphics g){ 
super.paintComponent(g); 
shape=ShapeMaker.makeShapeA((6+x)*dx,y*dy); 
Graphics2D g2=(Graphics2D)g; 
g2.setPaint(Color.RED); 
for(int i=0;i<=20;i++) 
g2.draw(new Line2D.Float(0,i*dy,12*dx,i*dy)); 
for(int i=0;i<=12;i++) 
g2.draw(new Line2D.Float(i*dx,0,i*dx,20*dy)); 

g2.setPaint(Color.GREEN); 
g2.fill(shape.createTransformedShape(t)); 
g2.setPaint(Color.BLUE); 
g2.draw(shape.createTransformedShape(t)); 


} 
//旋转方块,暂时由鼠标事件驱动 
public void rotate(){ 
t.setToRotation(Math.toRadians(90*i),(6+x)*dx,y*dy); 

i=(++i)%4; 
flag=(++flag)%4; 
} 
//旋转后的坐标系统好像发生了变化,此方法控制方块在变化后的坐标中继续向下移动 
public void moveDownY(){ 
y++; 
if(y+4>20) 
y=0; 
} 
//同moveX()相似,这两个方法的使用我还处于怀疑中,请指点 
public void moveDownX(){ 
x++; 
if(x+1>20-y) 
x=0; 
} 
//移动事件由定时器驱动 
public void actionPerformed(ActionEvent event){ 
if(flag==0) 
moveDownY(); 
if(flag==1) 
moveDownX(); 
repaint(); 
} 
} 
//主框架 
class GameFrame extends JFrame{ 
private GamePanel gamePanel; 
public GameFrame(float dx,float dy){ 
setTitle("俄罗斯方块"); 
setSize(400,640); 

Container contentPane=getContentPane(); 
gamePanel=new GamePanel(dx,dy); 
contentPane.add(gamePanel,BorderLayout.CENTER); 
//鼠标事件驱动方块旋转 
addMouseListener(new MouseAdapter(){ 
public void mouseClicked(MouseEvent e){ 
gamePanel.rotate(); 
} 
}); 
//此键盘事件为何不能工作,请指点 
addKeyListener(new KeyAdapter(){ 
public void KeyTyped(KeyEvent e){ 
if(e.getKeyText(e.getKeyCode()).equals("R")){ 
gamePanel.rotate(); 
} 
} 
}); 
} 
} 
//测试主程序 
public class GameTest{ 
public static void main(String[] args){ 
JFrame frame=new GameFrame(30,30); 
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
frame.show(); 
} 
} 

